#pragma once
#include <vector>
#include <algorithm> // for std::find
#include <iterator>  // for std::distance

template <class key, class val>
class oMap
{
public:
    oMap();
    ~oMap();
    bool set(key, val);
    bool hasKey(key);
    int find(key);
    val get(key);
    val& operator[](key);
    
private:
    std::vector<key> _key;
    std::vector<val> _val;
};

template <class key, class val>
oMap<key, val>::oMap() = default;

template <class key, class val>
oMap<key, val>::~oMap() = default;

template<class key, class val>
bool oMap<key, val>::set(key k, val v) {
    int num = this->find(k);
    if (num != -1) {
        this->_val[num] = v;
    }
    else {
        this->_key.push_back(k);
        this->_val.push_back(v);
    }
    return true;
}

template <class key, class val>
val oMap<key, val>::get(key k) {
    int num = this->find(k);
    if (num == -1) {
        return val{}; // 返回val类型的默认值而非NULL
    }
    return this->_val[num];
}

template<class key, class val>
int oMap<key, val>::find(key k) {
    auto s = std::find(this->_key.begin(), this->_key.end(), k);
    if (s != this->_key.end()) {
        return std::distance(this->_key.begin(), s);
    }
    return -1;
}

template<class key, class val>
val& oMap<key, val>::operator[](key k) {
    int num = this->find(k);
    if (num == -1) {
        this->_key.push_back(k);
        this->_val.push_back(val{}); // 添加默认构造的val
        return this->_val.back();
    }
    return this->_val[num];
}

template<class key, class val>
bool oMap<key, val>::hasKey(key k) {
    return this->find(k) != -1;
}
